package com.jz.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;


public class BaseDao<T> {
    private static ComboPooledDataSource comboPooledDataSource = null;
    QueryRunner queryRunner = null;

    static {
        comboPooledDataSource = new ComboPooledDataSource();
    }

    {
        queryRunner = new QueryRunner(comboPooledDataSource);
    }

    //封装增删改操作
    public int update(String sql, Object... params) {
        try {
            return queryRunner.update(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    //封装查询操作
    //单行查询
    public T querySingle(String sql, Class<T> clazz, Object... params) {
        try {
            return queryRunner.query(sql, new BeanHandler<T>(clazz), params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    //多行查询
    public List<T> queryMore(String sql, Class<T> clazz, Object... params) {
        try {
            return queryRunner.query(sql, new BeanListHandler<T>(clazz), params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    //聚合查询
    public int queryScar(String sql, Object... params) {
        try {
            return queryRunner.query(sql, new ScalarHandler<Number>(), params).intValue();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
